// pages/find/find.js
Page({

  /* 页面的初始数据 */
  data: {
    // 榜单数据
    toplist: [],
  },

  /* 生命周期函数--监听页面加载 */
  onLoad(options) {
    this.getTopMusic()
  },
  // 找榜单数据：不包含歌曲
  getToplist: function () {
    return new Promise(function (resolve, reject) {
      wx.request({
        url: 'http://localhost:3000/toplist',
        success: (result) => {
          const list = result.data.list.slice(0, )
          resolve(list)
        },
      })
    })
  },
  // 通过榜单找歌单：找歌单需要榜单的id，所以需要异步处理。当this.getToplist()数据获得时才执行下面代码
  getTopMusic: function () {
    const toplist = []
    this.getToplist().then(res => {
      res.forEach(item => {
        return new Promise(function (resolve, reject) {
          wx.request({
            url: 'http://localhost:3000/playlist/track/all?id=' + item.id + '&limit=3',
            success: (result) => {
              const songlist = result.data.songs
              item.songlist = songlist
              toplist.push(item)
              resolve(toplist)
            },
          })
        }).then(res => {
          this.setData({
            toplist: res
          })
        })
      });
    })
  },
  // 跳转页面
  linklistdetail:function(e){
     const index=e.currentTarget.dataset.index
     const toplist=this.data.toplist
     const itemdata=toplist[index]
    wx.navigateTo({
      url: '/pages/listdetail/listdetail',
      // 传递榜单数据
      success:function(res){
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: itemdata})
      }
    })
  },
  // 搜索框聚焦进行跳转
  searchlink:function(){
     wx.navigateTo({
       url: '/pages/search/search',
     })
  },
})